package com.thinkgem.jeesite.common.utils.wx;

import java.io.InputStream;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.thinkgem.jeesite.modules.config.entity.weixin.ConfigWechat;

public class ClientCustomSSL {
	public static String doRefund(String url,String data,ConfigWechat configWechat) throws Exception {
		//* 注意PKCS12证书 是从微信商户平台-》账户设置-》 API安全 中下载的 
		KeyStore keyStore  = KeyStore.getInstance("PKCS12");  
		InputStream instream = ClientCustomSSL.class.getClassLoader().getResourceAsStream("apiclient_cert.p12");//P12文件目录 
		try {  
			keyStore.load(instream, configWechat.getMchId().toCharArray());//这里写密码..默认是你的MCHID  
		} finally {  
		    instream.close();  
		}  
		// Trust own CA and all self-signed certs  
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,  
        		 configWechat.getMchId().toCharArray()).build();  
        // Allow TLSv1 protocol only  
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(  
                sslcontext, new String[] { "TLSv1" }, null,  
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
        
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();  
        // HttpGet httpget = new  
        // HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");  
        HttpPost httppost = new HttpPost(url);  
        StringEntity se = new StringEntity(data);  
        httppost.setEntity(se);  
        System.out.println("executing request" + httppost.getRequestLine()); 
        
        CloseableHttpResponse responseEntry = httpclient.execute(httppost);  
        HttpEntity entity = responseEntry.getEntity();  
		return EntityUtils.toString(entity, "UTF-8");
	}
}
